const router = require("koa-router")();
const util = require("../utils/util");
const Menu = require("../models/menuSchema");

router.prefix("/menu");

//菜单列表查询
router.get("/list", async (ctx) => {
    const { menuName, menuState } = ctx.request.query;
    const params = {};
    if (menuName) params.menuName = menuName;
    if (menuState) params.menuState = menuState;
    let rootList = (await Menu.find(params)) || [];

    // 不加这个判断，只能查到第一级的菜单
    if (rootList[0]._id) {
        const child = await Menu.find({ parentId: String(rootList[0]._id) });
        rootList = rootList.concat(child);
    }
    const permissionList = util.getTreeMenu(rootList, null, []);
    ctx.body = util.success(permissionList);
});

//菜单增删改
router.post("/operate", async (ctx) => {
    const { _id, action, ...params } = ctx.request.body;
    let res, info;
    try {
        if (action === "add") {
            res = await Menu.create(params);
            //创建
            info = "创建成功";
        } else if (action === "edit") {
            //编辑
            params.updateTime = new Date();
            res = await Menu.findByIdAndUpdate(_id, params);
            info = "编辑成功";
        } else {
            //删除
            res = await Menu.findByIdAndRemove(_id);
            await Menu.deleteMany({ parentId: { $all: [_id] } });
            info = "删除成功";
        }
        ctx.body = util.success("", info);
    } catch (error) {
        ctx.body = util.fail(error.stack);
    }
});

module.exports = router;
